<template>
    <div class="main">
        <!-- 管理员头部 -->
        <div>
            <el-space wrap :size="10">
                <el-input v-model="input" clearable placeholder="请输入管理员名称" />
                <el-button type="primary" :icon="Search" @click="handlerSearch">查找</el-button>
                <el-button type="primary" :icon="Edit" @click="handlerAddAdminUser">添加</el-button>
            </el-space>
        </div>
        <!-- 管理员列表 -->
        <div class="table">
            <el-table :data="tableData" style="width: 100%" border>
                <el-table-column prop="id" label="管理员ID" align="center" />
                <el-table-column prop="username" label="管理员名称" align="center" />
                <el-table-column prop="realname" label="真实姓名" align="center" />
                <el-table-column prop="phone" label="电话" align="center" />
                <el-table-column label="管理员角色" align="center">
                    <template #default="scope">
                        <template v-for="item in handlerRoleName(scope.row.roleIds)" :key="item">
                            <el-tag>{{ item.label }}</el-tag>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
                        <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 添加和修改弹出框 -->
            <el-dialog v-model="dialogFormVisible" :title="bool?'创建':'修改'" align-center destroy-on-close>
                <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules">
                    <el-form-item label="用户名" prop="username" class="is-required">
                        <el-input v-model="ruleForm.username" autocomplete="off"  :disabled="bool==false"/>
                    </el-form-item>
                    <el-form-item label="密码" prop="password" class="is-required" v-if="bool">
                        <el-input v-model.trim="ruleForm.password" type="password" autocomplete="off" show-password />
                    </el-form-item>
                    <el-form-item label="电话" prop="phone" class="is-required">
                        <el-input v-model.number="ruleForm.phone" />
                    </el-form-item>
                    <el-form-item label="真实姓名" prop="realname" class="is-required">
                        <el-input v-model="ruleForm.realname" />
                    </el-form-item>
                    <el-form-item label="角色"  :class="bool?'':'is-required'"  prop="roleIds">
                        <template #default="scope">
                            <el-select v-model="ruleForm.roleIds" multiple placeholder="请选择">
                                <el-option v-for="item in roleManage" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </template>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">{{bool?'新增':'修改'}}</el-button>
                        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
        <!-- 分页组件 -->
        <div>
            <Paging v-bind="pagingDatas" @page-change="pageChange"></Paging>
        </div>
        <el-backtop :right="100" :bottom="100" ref="main" target=".main"  :visibility-height="20" />
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick, watch } from 'vue'
import { Search, Edit } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ClassPagination } from "#/index";
import Paging from "@/components/paging/Paging.vue";
import { post } from "@/utils/http";
import type { FormInstance } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
const input = ref('')
const name = ref('')
//请求分页的数据
let pagingDatas = reactive(new ClassPagination)
const main = ref()  //滚动组件对象的引用
let bool = ref(true)//用来判断是创建和添加
const tableData: TypeAdminList[] = reactive([]) //管理员列表
const roleManage: TypeRoleManage[] = reactive([]) //角色枚举列表
const dialogFormVisible = ref(false)
//电话验证
const validatephone = (rule: any, value: any, callback: any) => {
    var regexp = /^1[3456789]\d{9}$/
    if (value === '') {
        return callback(new Error('请输入电话号码'))
    } else if (!regexp.test(value)) {
        callback(new Error('手机号码格式不正确'))
    }
    callback()
}
//  用户验证
const validateUsername = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入用户名'))
    }
    callback()
}
//密码验证
const validatepassword = (rule: any, value: any, callback: any) => {
    var regexp = /^\w{4,16}$/
    if (value === '') {
        callback(new Error('请输入密码'))
    } else if (!regexp.test(value)) {
        callback(new Error("密码必须是字母、数字、下划线,长度4-16位"))
    } else {
        callback()
    }
}
//姓名验证
const validaterealname = (rule: any, value: any, callback: any) => {
    var regexp = /^[\u4E00-\u9FA5]{1,}$/;
    if (value === '') {
        callback(new Error('请输入姓名'))
    } else if (!regexp.test(value)) {
        callback(new Error('姓名必须是中文'))
    }
    callback()
}
//添加弹出框绑定数据
const ruleForm = reactive({
    username: '', //用户名
    password: '', //密码
    phone: '', //电话
    realname: '', //姓名
    roleIds:[], //角色
    id:0,
})
const newRuleForm = reactive({...ruleForm})

const rules = reactive({
    username: [{ validator: validateUsername, trigger: 'blur' }],
    password: [{ validator: validatepassword, trigger: 'blur' }],
    phone: [{ validator: validatephone, trigger: 'blur' }],
    realname: [{ validator: validaterealname, trigger: 'blur' }],
})
//添加
const handlerAddAdminUser = () => {
    bool.value = true
    dialogFormVisible.value = true
    Object.assign(ruleForm,newRuleForm)
}
//修改
const handleEdit = (index: number, row: TypeAdminList) => {
    bool.value = false
    dialogFormVisible.value = true
    Object.assign(ruleForm,row)
}
//创建和修改确定
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            let date = {
                _gp:'admin',
                _mt:bool.value==true?'create':'edit',
                adminDTO:JSON.stringify({...ruleForm})
            }
            post(date).then(res=>{
                console.log(res);
                if(200==res.errno){
                    ElMessage.success(bool.value==true?"创建成功":'修改成功')
                    dialogFormVisible.value =false
                    loadAdministratorsList()
                }else{
                    ElMessage.error(res.errmsg) 
                }
            })
            console.log('submit!')
        } else {
            console.log('error submit!')
            return false
        }
    })
}

//重置
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

//加载管理员列表
const loadAdministratorsList = () => {
    let data = {
        _gp: 'admin',
        _mt: 'list',
        username: name.value,
        page: pagingDatas.page,
        limit: pagingDatas.limit
    }
    post(data).then(res => {
        console.log(res);
        if (200 == res.errno) {
            tableData.length = 0
            tableData.push(...res.data.items)
            pagingDatas.total = res.data.total
            return Promise.resolve()
        } else {
            return Promise.reject(res.errmsg)
        }
    }).then(() => {
        //角色枚举请求数据
        let data = {
            _gp: "admin.role",
            _mt: "options",
        }
        post(data).then(res => {
            console.log(res);
            if (200 == res.errno) {
                roleManage.length = 0
                roleManage.push(...res.data)
            } else {
                return Promise.reject(res.errmsg)
            }
        })
    })
}
loadAdministratorsList()
//删除
const handleDelete = (index: number, row: TypeAdminList) => {
    let data = {
        _gp: 'admin',
        _mt: 'delete',
        id: row.id
    }
    ElMessageBox.confirm(
        '请问是否删除',
        '消息提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    )
        .then(() => {
            post(data).then(res => {
                if (200 == res.errno) {
                    ElMessage.success('删除成功')
                    loadAdministratorsList()
                } else {
                    ElMessage.error(res.errmsg)
                }
            })

        })
        .catch(() => {
            ElMessage.info('取消操作')
        })
}
//获取角色枚举名字
const handlerRoleName = (roleIds: number[]) => {
    let data = Array.prototype.concat.apply([], roleIds)
    if (data.length == 0) return [];
    return roleManage.filter(v => data.includes(v.value))
}
//分页组件每次调用事件
function pageChange(e: TypePaGing) {
    pagingDatas.page = e._page
    pagingDatas.limit = e._limit
    loadAdministratorsList()
    nextTick(() => {
        main.value.$el.click?.()
    })
}

//搜索
const handlerSearch = () => {
    name.value = input.value
    pagingDatas.page = 1
    loadAdministratorsList()
}

</script>
<style lang="less" scoped>
.main {
    >div {
        margin: 15px 0px;

        .el-input {
            width: 15vw;
        }
    }

    .table {
        .el-tag {
            margin-right: 5px;
            margin-bottom: 4px;
        }

        .el-dialog {
            text-align: center;

            .el-form {
                &::v-deep .el-form-item__label {
                    width: 14vw;
                }

                .el-form-item__content {
                    .el-input {
                        width: 25vw;
                    }
                }
            }
        }
    }
}
</style>